package com.example.activiti.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.activiti.common.constant.PublicKeyword;
import com.example.activiti.dto.publicDto.ActivitiResponseDto;

@Service
public class HistoryManagerService {
	@Resource
    private HistoryService historyService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private RepositoryService repositoryService;
	
	/**
	 * 根据起始人获取他发起的所有的流程实例
	 * @return
	 */
	public List<HistoricProcessInstance> getIdentityByCreateUser(String assignee) {
		List<HistoricProcessInstance> historicProcessInstanceList = historyService
				.createHistoricProcessInstanceQuery()
				.startedBy(assignee)
				.list();
		return historicProcessInstanceList;
	}
	
	/**
	 * 获取所有的正常存活的未结束或删除的流程实例
	 * @return
	 */
	public List<ActivitiResponseDto> getAllSurvivalInstance(){
		List<ActivitiResponseDto> responseList = new ArrayList<ActivitiResponseDto>();
		List<ProcessInstance> instanceList = runtimeService.createProcessInstanceQuery().list();
		for(ProcessInstance instance:instanceList) {
			Task task = taskService.createTaskQuery()
					.processInstanceId(instance.getId()).singleResult();
			Map<String, Object> paramMap = taskService.getVariables(task.getId());
			ActivitiResponseDto response = new ActivitiResponseDto();
			response.setAssignee(task.getAssignee());
			response.setInstanceId(instance.getId());
			response.setLastTaskId(task.getId());
			response.setParamMap(paramMap);
			response.setProcessDefinitionId(instance.getProcessDefinitionId());
			response.setProcessDefinitionName(instance.getProcessDefinitionName());
			Object taskCheckAssigneeObj = paramMap.get(PublicKeyword.OPINION);
			if(taskCheckAssigneeObj!=null) {
				response.setTaskCheckAssignee(taskCheckAssigneeObj.toString());
			}
			Object checkStatusObj = paramMap.get(PublicKeyword.CHECKSTATUS);
			if(checkStatusObj!=null) {
				response.setCheckStatus(Integer.parseInt(checkStatusObj.toString()));
			}
			responseList.add(response);
		}
		return responseList;
	}
	
	/**
	 * 获取当前任务审批人
	 */
	public UserTask getInstanceInUser(String istanceId) {
		Task task=taskService.createTaskQuery().processInstanceId(istanceId).singleResult();
        if (task==null){
            throw new RuntimeException("流程未启动或已执行完成");
        }
        // 取得已提交的任务
        HistoricTaskInstance historicTaskInstance = historyService
        		.createHistoricTaskInstanceQuery()
                .taskId(task.getId()).singleResult();
        // 取得正在流转的流程实例,若已完成则为null
        //获得流程定义
        ProcessDefinition processDefinition=repositoryService.getProcessDefinition(historicTaskInstance.getProcessDefinitionId());
        //获得当前流程的活动ID
        Execution execution = runtimeService
        		.createExecutionQuery()
        		.executionId(historicTaskInstance.getExecutionId())
        		.singleResult();
        String activityId=execution.getActivityId();
        UserTask userTask =null;
        while (true){
            //根据活动节点获取当前的组件信息
            FlowNode flowNode =getFlowNode(processDefinition.getId(),activityId);
            SequenceFlow sequenceFlow = flowNode.getIncomingFlows().get(0);
        	//获取上一节点
//        	FlowElement beforeElement = sequenceFlow.getSourceFlowElement();
        	//获取下一节点
        	FlowElement nextElement = sequenceFlow.getTargetFlowElement();
        	userTask = (UserTask) nextElement;
            return userTask;
        }
	}
	
	/**
     * 根据活动节点和流程定义ID获取该活动节点的组件信息
     * @param processDefinitionId
     * @param activityId
     * @return
     */
    public FlowNode getFlowNode(String processDefinitionId,String activityId){
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(activityId);
        return flowNode;
    }
    
    
}












